package com.ybu.service.impl;

import com.ybu.common.ServiceCode;
import com.ybu.common.ServiceException;
import com.ybu.mapper.CartMapper;
import com.ybu.pojo.entity.Cart;
import com.ybu.pojo.vo.CartVO;
import com.ybu.pojo.vo.UserLoginVO;

import com.ybu.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    private CartService cartService;
    @Override
    public List<CartVO> getCartList(UserLoginVO userLoginVO) {
        List<CartVO> cartList = cartMapper.getCartList(userLoginVO.getId());
        if(cartList==null || cartList.size()==0){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户购物车为空");
        }
        return cartList;

    }
    @Override
    public void deleteCartItem(Integer[] ids,Integer userId) {
//
//        Cart result= cartMapper.findById(id);
//        if (result==null){
//            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, ("收货地址不存在"));
//        }
//        if (result.getId()!=userId){
//            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,("非法数据访问"));
//        }
        // 执行删除操作
        cartMapper.deleteCartItemById(ids, userId);

    }


    @Override
    public List<CartVO> update(Integer id,Integer userId, Integer productId, Integer num) {

        Cart cart = cartMapper.findById(id);
        if (cart == null) {
            //所以，如果购物车中没有这个商品；这就表示是有问题的；那么我们就不进行这个更新操作；返回“更新失败”异常；
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,("商品不存在,更新失败"));
        } else {
            Cart cartNew = new Cart();
            cartNew.setNum(num);
            cartNew.setId(cart.getId());
            cartNew.setProductId(cart.getProductId());
            cartNew.setUserId(cart.getUserId());
            cartNew.setPrice(cart.getPrice());
           int result= cartMapper.updateNum(cartNew.getId(),cartNew.getUserId(),cartNew.getProductId(),cartNew.getNum());
            if (result != 1) {
                throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "更新失败");
            }
        }
return null;
    }

}





